// 表单重置
export function resetForm (this: any, refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields()
  }
}

// 回显数据字典
export function selectDictLabel (datas, value) {
  const actions = []
  Object.keys(datas).some((key) => {
    if (datas[key].dictValue === ('' + value)) {
      // @ts-ignore
      actions.push(datas[key].dictLabel)
      return true
    }
  })
  return actions.join('')
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty (str) {
  if (!str || str === 'undefined' || str === 'null') {
    return ''
  }
  return str
}

// 给参数添加日期范围
export function addDateRange (params, dateRange, propName) {
  const search = params
  search.params = {}
  // eslint-disable-next-line eqeqeq
  if (dateRange != null && dateRange != '') {
    if (typeof (propName) === 'undefined') {
      search.params.beginTime = dateRange[0]
      search.params.endTime = dateRange[1]
    } else {
      search.params['begin' + propName] = dateRange[0]
      search.params['end' + propName] = dateRange[1]
    }
  }
  return search
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree (data, id, parentId, children) {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  }

  const childrenListMap = {}
  const nodeIds = {}
  const tree = []

  for (const d of data) {
    const parentId = d[config.parentId]
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[parentId].push(d)
  }

  for (const d of data) {
    const parentId = d[config.parentId]
    if (nodeIds[parentId] == null) {
      // @ts-ignore
      tree.push(d)
    }
  }

  for (const t of tree) {
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    adaptToChildrenList(t)
  }

  function adaptToChildrenList (o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c)
      }
    }
  }
  return tree
}
